import tempfile
import subprocess
import sys

def run_bash(command: str, sudo: bool = False, timeout: float | None = None):
    # try:
    #     output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT, universal_newlines=True)
    #     return {'success': True, 'output': output}
    # except subprocess.CalledProcessError as e:
    #     return {'success': False, 'message': f'Error: {e}', 'output': e.output}
    with tempfile.NamedTemporaryFile('w', suffix='.sh') as f:
        f.write(command)
        f.flush()
        shell = ['bash', '-e', f.name]
        if sudo:
            shell = ['sudo', '-S'] + shell
        with subprocess.Popen(shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
            result = b''
            accum = b''
            while p.poll() is None:
                try:
                    stdout, stderr = p.communicate(b'y\n', timeout=timeout)
                    assert stderr is None
                except subprocess.TimeoutExpired:
                    p.kill()
                    result += b'\n[Timeout expired]'
                    break
                else:
                    accum += stdout
                    try:
                        sys.stdout.write(accum.decode())
                        accum = b''
                        sys.stdout.flush()
                    except UnicodeDecodeError:
                        pass
                    result += stdout
            try:
                result = result.decode()
            except UnicodeDecodeError:
                try:
                    result = result.decode('latin1')
                except UnicodeDecodeError:
                    result = ''
            try:
                p.wait(timeout=2)
            except subprocess.TimeoutExpired:
                pass
            result = {'output': result, 'exit_code': p.returncode}
    return result
